import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigService, ConfigModule } from '@nestjs/config';
import envConfig from './config/env';
import { TypeOrmModule } from '@nestjs/typeorm';

import { RedisModule } from './redis/redis.module';
import { AuthModule } from './modules/auth/auth.module';
import { FileModule } from './modules/file/file.module';
import { PostsModule } from './modules/posts/posts.module';
import { UsersModule } from './modules/users/users.module';
import { CommentsModule } from './modules/comments/comments.module';
import { PageModule } from './modules/page/page.module';
import { SmtpModule } from './modules/smtp/smtp.module';
import { HistoriesModule } from './modules/histories/histories.module';
import { TagsModule } from './modules/tags/tags.module';
import { WorksModule } from './modules/works/works.module';
import { CategoriesModule } from './modules/categories/categories.module';
import { SiteModule } from './modules/site/site.module';
import { ExternalModule } from './modules/external/external.module';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { LoggerMiddleware } from './middleware/logger.middleware'; // 全局日志中间件
import winstonLogger from './config/winston.config';

import { resolve } from 'path';
import { WinstonModule } from 'nest-winston';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // 设置为全局
      cache: true,
      envFilePath: [envConfig.path],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql', // 数据库类型
        // entities: [],  // 数据表实体
        entities: ['dist/**/*.entity{.ts,.js}'],
        host: configService.get('DB_HOST'), // 主机，默认为localhost
        port: configService.get<number>('DB_PORT'), // 端口号
        username: configService.get('DB_USER'), // 用户名
        password: configService.get('DB_PASSWORD'), // 密码
        database: configService.get('DB_DATABASE'), //数据库名
        timezone: '+08:00', //服务器上配置的时区
        synchronize: true, //根据实体自动创建数据库表， 生产环境建议关闭
        autoLoadEntities: true, // 自动导入实体
        maxQueryExecutionTime: 1000, // 记录超过1秒的查询
      }),
    }),
    MailerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        const SMTP_HOST = configService.get('SMTP_HOST');
        const SMTP_PORT = configService.get('SMTP_PORT');
        const SMTP_USER = configService.get('SMTP_USER');
        const SMTP_PASS = configService.get('SMTP_PASS');
        const SMTP_FROM = configService.get('SMTP_FROM');
        return {
          transport: {
            host: SMTP_HOST,
            port: SMTP_PORT,
            secure: false, // upgrade later with STARTTLS
            requireTLS: true,
            auth: {
              user: SMTP_USER,
              pass: SMTP_PASS,
            },
          },
          defaults: {
            from: SMTP_FROM,
          },
          template: {
            dir: resolve(__dirname, 'templates'),
            adapter: new HandlebarsAdapter(),
          },
        };
      },
    }),
    WinstonModule.forRoot({
      transports: winstonLogger.transports,
      format: winstonLogger.format,
      defaultMeta: winstonLogger.defaultMeta,
      exitOnError: false, // 防止意外退出
    }),
    PostsModule,
    UsersModule,
    AuthModule,
    FileModule,
    RedisModule,
    CommentsModule,
    PageModule,
    SmtpModule,
    HistoriesModule,
    TagsModule,
    WorksModule,
    CategoriesModule,
    SiteModule,
    ExternalModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
